from django.shortcuts import render, redirect
from django.urls import reverse

from apps.book.models import Author
from apps.common.pagination import LxgPageNation


def author_list(request):
    page = LxgPageNation(request, Author, 12)
    authors = page.get_objects()
    page_html = page.get_page_html()
    context = {'authors': authors, 'page': page_html}
    return render(request, 'book/author/author_list.html', context)


def author_add(request):
    # POST
    if request.method == 'POST':
        name = request.POST.get('name')
        gender = request.POST.get('gender')
        birthday = request.POST.get('birthday')
        phone = request.POST.get('phone')
        wechat = request.POST.get('wechat')
        qq = request.POST.get('qq')
        email = request.POST.get('email')
        Author.objects.create(
            name=name,
            gender=gender,
            birthday=birthday,
            phone=phone,
            wechat=wechat,
            qq=qq,
            email=email
        )
        return redirect(reverse('book:author_list'))
    # GET
    return render(request, 'book/author/author_add.html')


def author_edit(request):
    context = {}
    # POST
    if request.method == 'POST':
        id = request.POST.get('id')
        name = request.POST.get('name')
        gender = request.POST.get('gender')
        birthday = request.POST.get('birthday')
        phone = request.POST.get('phone')
        wechat = request.POST.get('wechat')
        qq = request.POST.get('qq')
        email = request.POST.get('email')
        # 修改
        author = Author.objects.get(id=id)
        author.name = name
        author.gender = gender
        author.birthday = birthday
        author.phone = phone
        author.wechat = wechat
        author.qq = qq
        author.email = email
        author.save()
        return redirect(reverse('book:author_list'))

    # GET
    id = request.GET.get('id')
    author = Author.objects.get(id=id)
    author.birthday = author.birthday.strftime('%Y-%m-%d')
    context['author'] = author
    return render(request, 'book/author/author_edit.html', context)


def author_delete(request):
    id = request.GET.get('id')
    Author.objects.get(id=id).delete()
    return redirect(reverse('book:author_list'))
